/**
 * 
 */
package std.game.objects.views;

import static net.wimpi.telnetd.io.terminal.ColorHelper.BOLD;
import static net.wimpi.telnetd.io.terminal.ColorHelper.colorizeText;
import static utils.WordUtils.affixIndefiniteArticle;
import groovy.text.Template;
import groovy.text.TemplateEngine;


import org.apache.log4j.Logger;
import org.codehaus.groovy.control.CompilationFailedException;
import org.groovymud.object.MudObject;
import org.groovymud.object.alive.Alive;
import org.groovymud.object.views.View;
import org.groovymud.utils.text.IncludeTemplateEngine
import org.groovymud.object.MudObjectWithNameAndDescription;

/**
 * @author matt
 * 
 */
public class MudObjectView<T extends MudObjectWithNameAndDescription> implements View<T> {
	
	private transient final static Logger logger = Logger.getLogger(MudObjectView.class);
    static final String DYNAMIC_DESCRIPTION_HEADER = """
			<%
			import static utils.WordUtils.*;\n
            import static org.groovymud.utils.NumberToWordConverter.*
            %>"""

    public void writeLookHeader(Alive looker, T object) {
		try {
			looker.getTerminalOutput().writeln("You see " + affixIndefiniteArticle(object.getName().toString()) + ":");
		} catch (IOException e) {
			logger.error(e, e);
		}
	}
	
	public void writeLookBody(Alive looker, T object) {
		if (object.getDescription() != null) {
			writeDynamicText(looker, object, object.getDescription());
		}
	}
	
	public void writeDynamicText(Alive looker, T target, String text) {
        def binding
        def template
        def stream = looker.getTerminalOutput();
        (template, binding) = createTemplate(target, looker, text)
        stream.writeln(colorizeText(makeTemplateAsString(template, binding), BOLD));
    }

    private String makeTemplateAsString(Template template, HashMap binding) {
        return template.make(binding).toString()
    }

    private List createTemplate(T target, Alive looker, String text) {
        Map binding = new HashMap();
        binding.put("it", target);
        binding.put("looker", looker);
        TemplateEngine engine = new IncludeTemplateEngine();
        Template template;
        try {
            // auto import some utils
            template = engine.createTemplate(DYNAMIC_DESCRIPTION_HEADER + text);

        } catch (CompilationFailedException e) {
            logger.error(e, e);
        } catch (ClassNotFoundException e) {
            logger.error(e, e);
        } catch (IOException e) {
            logger.error(e, e);
        }
        return [template, binding]
    }

    void writeLookFooter(Alive looker, T object) {

    }


}
